package com.sheliduan.itlearning.blogger.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sheliduan.itlearning.blogger.model.vos.home.DailyIncomeVO;
import com.sheliduan.itlearning.blogger.model.vos.home.HomeStatisticsRspVO;
import com.sheliduan.itlearning.common.domain.dos.ArticleCourseDO;
import com.sheliduan.itlearning.common.domain.dos.OrderDO;
import com.sheliduan.itlearning.common.domain.dos.UserDO;
import com.sheliduan.itlearning.common.domain.dos.VideoCourseDO;
import com.sheliduan.itlearning.common.domain.mapper.ArticleCourseMapper;
import com.sheliduan.itlearning.common.domain.mapper.OrderMapper;
import com.sheliduan.itlearning.common.domain.mapper.UserMapper;
import com.sheliduan.itlearning.common.domain.mapper.VideoCourseMapper;
import com.sheliduan.itlearning.common.model.vos.IdReqVO;
import com.sheliduan.itlearning.common.utils.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/blogger/home")
public class BloggerHomeController {

    @Autowired
    private ArticleCourseMapper articleCourseMapper;

    @Autowired
    private VideoCourseMapper videoCourseMapper;

    @Autowired
    private OrderMapper orderMapper;

    private static final SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat("MM-dd");

    @PostMapping("/statistics")
    public ResponseData getHomeStatistics(@RequestBody @Validated IdReqVO reqVO) {
        Integer bloggerId = reqVO.getId();
        // 1. 统计图文课程数量（status为2或4）
        Long articleCount = articleCourseMapper.selectCount(new LambdaQueryWrapper<ArticleCourseDO>()
                .eq(ArticleCourseDO::getUserId, bloggerId)
                .in(ArticleCourseDO::getStatus, 2, 4));

        // 2. 统计视频课程数量（status为2或4）
        Long videoCount = videoCourseMapper.selectCount(new LambdaQueryWrapper<VideoCourseDO>()
                .eq(VideoCourseDO::getUserId, bloggerId)
                .in(VideoCourseDO::getStatus, 2, 4));

        // 3. 统计图文课程观看量
        List<ArticleCourseDO> articleCourseDOS = articleCourseMapper.selectList(new LambdaQueryWrapper<ArticleCourseDO>()
                .eq(ArticleCourseDO::getUserId, bloggerId)
                .in(ArticleCourseDO::getStatus, 2, 4));
        Long articleWatchNums = 0L;
        for (ArticleCourseDO articleCourseDO : articleCourseDOS) {
            articleWatchNums += articleCourseDO.getWatchNums();
        }

        // 4. 统计视频课程观看量
        List<VideoCourseDO> videoCourseDOS = videoCourseMapper.selectList(new LambdaQueryWrapper<VideoCourseDO>()
                .eq(VideoCourseDO::getUserId, bloggerId)
                .in(VideoCourseDO::getStatus, 2, 4));
        Long videoWatchNums = 0L;
        for (VideoCourseDO videoCourseDO : videoCourseDOS) {
            videoWatchNums += videoCourseDO.getWatchNums();
        }
        // 5. 统计近30天每日收益
        Calendar calendar = Calendar.getInstance();
        Date endDate = calendar.getTime();
        calendar.add(Calendar.DAY_OF_MONTH, -29);
        Date startDate = calendar.getTime();
        // 该博主图文、视频下的所有课程id(去重后)
        Set<Integer> courseIds = new HashSet<>();
        LambdaQueryWrapper<ArticleCourseDO> wrapperArticle = Wrappers.lambdaQuery();
        wrapperArticle.eq(ArticleCourseDO::getUserId, bloggerId);
        for (ArticleCourseDO articleCourseDO : articleCourseMapper.selectList(wrapperArticle)) {
            courseIds.add(articleCourseDO.getId());
        }
        LambdaQueryWrapper<VideoCourseDO> wrapperVideo = Wrappers.lambdaQuery();
        wrapperVideo.eq(VideoCourseDO::getUserId, bloggerId);
        for (VideoCourseDO videoCourseDO : videoCourseMapper.selectList(wrapperVideo)) {
            courseIds.add(videoCourseDO.getId());
        }
        List<Integer> ids = new ArrayList<>(courseIds);
        List<OrderDO> orderDOS = orderMapper.selectList(ids, null, startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(), endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
        // 按日期分组统计收益
        Map<String, Double> dailyIncomeMap = orderDOS.stream()
                .collect(Collectors.groupingBy(
                        order -> DATE_FORMATTER.format(order.getOrderTime()),
                        Collectors.summingDouble(OrderDO::getPrice)
                ));

        // 生成30天的日期列表，确保没有订单的日期也显示为0
        List<DailyIncomeVO> dailyIncomes = new ArrayList<>();
        calendar.setTime(startDate);
        for (int i = 0; i < 30; i++) {
            String dateStr = DATE_FORMATTER.format(calendar.getTime());
            double income = dailyIncomeMap.getOrDefault(dateStr, 0.0);
            dailyIncomes.add(DailyIncomeVO.builder()
                    .date(dateStr)
                    .income(income)
                    .build());
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }

        // 构建返回对象
        HomeStatisticsRspVO rspVO = HomeStatisticsRspVO.builder()
                .articleCount(articleCount)
                .videoCount(videoCount)
                .articleWatchNums(articleWatchNums)
                .videoWatchNums(videoWatchNums)
                .dailyIncomes(dailyIncomes)
                .build();

        return ResponseData.success(rspVO);
    }
}
